<!-- 地图显示组件 -->
<template>
  <div class="map-viewer">
    <div class="map-header">
      <div class="map-controls">
        <el-button-group class="view-switcher">
          <el-button
            :type="activeView === '3d' ? 'primary' : ''"
            @click="switchView('3d')"
          >
            <el-icon><View /></el-icon>
            三维态势
          </el-button>
          <el-button
            :type="activeView === '2d' ? 'primary' : ''"
            @click="switchView('2d')"
          >
            <el-icon><Map /></el-icon>
            二维态势
          </el-button>
        </el-button-group>
        
        <div class="map-tools">
          <el-button size="small" @click="resetView">
            <el-icon><RefreshRight /></el-icon>
            重置视角
          </el-button>
          <el-button size="small" @click="toggleFullscreen">
            <el-icon><FullScreen /></el-icon>
            全屏
          </el-button>
        </div>
      </div>
      
      <div class="status-bar" v-if="mapStatus">
        <div class="coordinate-display">
          <span class="coord-label">坐标:</span>
          <span class="coord-value">{{ mapStatus.coordinates }}</span>
        </div>
        <div class="zoom-display">
          <span class="zoom-label">缩放:</span>
          <span class="zoom-value">{{ mapStatus.zoom }}</span>
        </div>
      </div>
    </div>
    
    <div class="map-container">
      <div
        v-show="activeView === '3d'"
        id="cesium-container"
        class="map-display cesium-map"
        @drop="handleDrop"
        @dragover.prevent
      ></div>
      
      <div
        v-show="activeView === '2d'"
        id="openlayers-container"
        class="map-display openlayers-map"
        @drop="handleDrop"
        @dragover.prevent
      ></div>
      
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-overlay">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p class="loading-text">地图加载中...</p>
      </div>
      
      <!-- 错误状态 -->
      <div v-if="hasError && !isLoading" class="error-overlay">
        <div class="error-content">
          <el-icon class="error-icon"><Warning /></el-icon>
          <p class="error-text">地图加载失败</p>
        </div>
        <div class="error-actions">
          <el-button class="retry-button" @click="retryLoad">
            重新加载
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 地图图例 -->
    <div class="map-legend" v-if="deployedEquipment.length > 0">
      <div class="legend-header">
        <h4>图例</h4>
        <el-button size="small" text @click="toggleLegend">
          <el-icon v-if="showLegend"><CaretTop /></el-icon>
          <el-icon v-else><CaretBottom /></el-icon>
        </el-button>
      </div>
      <div v-show="showLegend" class="legend-content">
        <div class="legend-item" v-for="type in equipmentTypes" :key="type.key">
          <div :class="['legend-marker', type.key]"></div>
          <span class="legend-label">{{ type.label }}</span>
          <span class="legend-count">{{ getEquipmentCount(type.key) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as Cesium from 'cesium'
import * as ol from 'ol'
import 'ol/ol.css'
import { View, RefreshRight, FullScreen, Loading, Warning, CaretTop, CaretBottom } from '@element-plus/icons-vue'

const props = defineProps({
  routeData: {
    type: Object,
    default: () => null
  },
  isPlanning: {
    type: Boolean,
    default: false
  },
  planningMode: {
    type: String,
    default: 'ship'
  }
})

const emit = defineEmits(['mapClick', 'equipmentDrop'])

const activeView = ref('3d')
const isLoading = ref(true)
const hasError = ref(false)
const showLegend = ref(true)
const mapStatus = ref(null)
const deployedEquipment = ref([])

let cesiumViewer = null
let openLayersMap = null

const equipmentTypes = [
  { key: 'radar', label: '雷达设备', color: '#409EFF' },
  { key: 'jammer', label: '干扰设备', color: '#E6A23C' },
  { key: 'ship', label: '舰船', color: '#67C23A' },
  { key: 'aircraft', label: '战机', color: '#F56C6C' }
]

const getEquipmentCount = (type) => {
  return deployedEquipment.value.filter(eq => eq.category === type).length
}

const switchView = (view) => {
  activeView.value = view
  setTimeout(() => {
    if (view === '3d' && !cesiumViewer) {
      initCesium()
    } else if (view === '2d' && !openLayersMap) {
      initOpenLayers()
    }
  }, 100)
}

const resetView = () => {
  if (activeView.value === '3d' && cesiumViewer) {
    cesiumViewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(120.0, 35.0, 10000000.0)
    })
  } else if (activeView.value === '2d' && openLayersMap) {
    openLayersMap.getView().setCenter([0, 0])
    openLayersMap.getView().setZoom(2)
  }
  ElMessage.success('视角已重置')
}

const toggleFullscreen = () => {
  const mapContainer = document.querySelector('.map-container')
  if (!document.fullscreenElement) {
    mapContainer.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const toggleLegend = () => {
  showLegend.value = !showLegend.value
}

const retryLoad = () => {
  hasError.value = false
  isLoading.value = true
  if (activeView.value === '3d') {
    initCesium()
  } else {
    initOpenLayers()
  }
}

const handleDrop = (event) => {
  event.preventDefault()
  const equipmentData = event.dataTransfer.getData('equipment')
  if (equipmentData) {
    const equipment = JSON.parse(equipmentData)
    const coordinates = getCoordinatesFromEvent(event)
    if (coordinates) {
      deployEquipment(equipment, coordinates)
      emit('equipmentDrop', { equipment, coordinates })
    }
  }
}

const getCoordinatesFromEvent = (event) => {
  if (activeView.value === '3d' && cesiumViewer) {
    const cartesian = cesiumViewer.camera.pickEllipsoid(
      new Cesium.Cartesian2(event.offsetX, event.offsetY),
      cesiumViewer.scene.globe.ellipsoid
    )
    if (cartesian) {
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
      return [
        Cesium.Math.toDegrees(cartographic.longitude),
        Cesium.Math.toDegrees(cartographic.latitude),
        cartographic.height
      ]
    }
  } else if (activeView.value === '2d' && openLayersMap) {
    const coordinate = openLayersMap.getCoordinateFromPixel([event.offsetX, event.offsetY])
    const lonLat = ol.proj.toLonLat(coordinate)
    return [lonLat[0], lonLat[1], 0]
  }
  return null
}

const deployEquipment = (equipment, coordinates) => {
  const deployedItem = {
    ...equipment,
    deployedId: Date.now(),
    coordinates,
    status: 'active'
  }
  
  deployedEquipment.value.push(deployedItem)
  
  // 在地图上添加标记
  addEquipmentMarker(deployedItem)
  
  ElMessage.success(`${equipment.name} 部署成功`)
}

const addEquipmentMarker = (equipment) => {
  if (activeView.value === '3d' && cesiumViewer) {
    cesiumViewer.entities.add({
      id: equipment.deployedId,
      position: Cesium.Cartesian3.fromDegrees(
        equipment.coordinates[0],
        equipment.coordinates[1],
        equipment.coordinates[2] || 0
      ),
      billboard: {
        image: getEquipmentIcon(equipment.category),
        scale: 0.8,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM
      },
      label: {
        text: equipment.name,
        font: '14pt sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, -50),
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE
      }
    })
  }
}

const getEquipmentIcon = (category) => {
  const icons = {
    radar: '📡',
    jammer: '📶',
    ship: '🚢',
    aircraft: '✈️'
  }
  return icons[category] || '📍'
}

const initCesium = () => {
  try {
    isLoading.value = true
    hasError.value = false
    
    cesiumViewer = new Cesium.Viewer('cesium-container', {
      terrainProvider: new Cesium.EllipsoidTerrainProvider(),
      animation: false,
      timeline: false,
      fullscreenButton: false,
      vrButton: false,
      geocoder: false,
      homeButton: false,
      infoBox: false,
      sceneModePicker: false,
      selectionIndicator: false,
      navigationHelpButton: false,
      baseLayerPicker: false,
      creditContainer: document.createElement('div')
    })
    
    // 设置默认视角
    cesiumViewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(120.0, 35.0, 5000000.0)
    })
    
    // 添加点击事件
    cesiumViewer.screenSpaceEventHandler.setInputAction((click) => {
      if (props.isPlanning) {
        const cartesian = cesiumViewer.camera.pickEllipsoid(
          click.position,
          cesiumViewer.scene.globe.ellipsoid
        )
        if (cartesian) {
          const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
          const coordinates = [
            Cesium.Math.toDegrees(cartographic.longitude),
            Cesium.Math.toDegrees(cartographic.latitude),
            cartographic.height
          ]
          emit('mapClick', coordinates)
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    
    // 添加鼠标移动事件
    cesiumViewer.screenSpaceEventHandler.setInputAction((movement) => {
      const cartesian = cesiumViewer.camera.pickEllipsoid(
        movement.endPosition,
        cesiumViewer.scene.globe.ellipsoid
      )
      if (cartesian) {
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
        const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6)
        const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6)
        mapStatus.value = {
          coordinates: `${longitude}°, ${latitude}°`,
          zoom: Math.round(cesiumViewer.camera.getMagnitude() / 1000) + 'km'
        }
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    
    isLoading.value = false
  } catch (error) {
    console.error('Cesium初始化失败:', error)
    hasError.value = true
    isLoading.value = false
  }
}

const initOpenLayers = () => {
  try {
    isLoading.value = true
    hasError.value = false
    
    const { Map, View } = ol
    const { Tile: TileLayer } = ol.layer
    const { OSM } = ol.source
    
    openLayersMap = new Map({
      target: 'openlayers-container',
      layers: [
        new TileLayer({
          source: new OSM()
        })
      ],
      view: new View({
        center: ol.proj.fromLonLat([120.0, 35.0]),
        zoom: 6
      })
    })
    
    // 添加点击事件
    openLayersMap.on('click', (event) => {
      if (props.isPlanning) {
        const coordinate = event.coordinate
        const lonLat = ol.proj.toLonLat(coordinate)
        emit('mapClick', [lonLat[0], lonLat[1], 0])
      }
    })
    
    isLoading.value = false
  } catch (error) {
    console.error('OpenLayers初始化失败:', error)
    hasError.value = true
    isLoading.value = false
  }
}

// 监听路由数据变化
watch(() => props.routeData, (newRoute) => {
  if (newRoute && newRoute.points && newRoute.points.length > 1) {
    drawRoute(newRoute)
  }
}, { deep: true })

const drawRoute = (route) => {
  if (activeView.value === '3d' && cesiumViewer) {
    cesiumViewer.entities.add({
      name: route.name || '航线',
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(
          route.points.flat()
        ),
        width: 3,
        material: route.type === 'ship' ? Cesium.Color.BLUE : Cesium.Color.RED,
        clampToGround: route.type === 'ship'
      }
    })
  }
}

onMounted(() => {
  setTimeout(() => {
    initCesium()
  }, 100)
})

onBeforeUnmount(() => {
  if (cesiumViewer) {
    cesiumViewer.destroy()
  }
  if (openLayersMap) {
    openLayersMap.setTarget(null)
  }
})

defineExpose({
  addRoutePoint: (point) => {
    // 父组件可以调用此方法添加航路点
  },
  clearRoute: () => {
    if (cesiumViewer) {
      cesiumViewer.entities.removeAll()
    }
  }
})
</script>

<style scoped>
.map-viewer {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.map-header {
  background: #1f2d3d; /* 深色背景 */
  border-bottom: 1px solid #2d3a4b; /* 深色边框 */
  padding: 1vh 1.5vw;
}

.map-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1vh;
}

.view-switcher .el-button {
  height: 3.5vh;
  font-size: 0.85rem;
}

.map-tools {
  display: flex;
  gap: 0.8vw;
}

.status-bar {
  display: flex;
  gap: 2vw;
  font-size: 0.8rem;
  color: #8591a3; /* 深色主题次要文字 */
}

.coord-label, .zoom-label {
  font-weight: 500;
}

.coord-value, .zoom-value {
  font-family: 'Monaco', 'Consolas', monospace;
  color: #bfcbd9; /* 深色主题主要文字 */
}

.map-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.map-display {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.loading-overlay, .error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.7);
  z-index: 1000;
}

.error-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 5vh; /* 增加内容和按钮之间的距离 */
}

.error-actions {
  display: flex;
  justify-content: center;
  margin-top: 4vh; /* 按钮进一步向下移动 */
}

.loading-icon, .error-icon {
  font-size: 3rem;
  margin-bottom: 1vh;
}

.loading-icon {
  color: var(--el-color-primary);
  animation: rotate 2s linear infinite;
}

.error-icon {
  color: var(--el-color-danger);
}

.loading-text, .error-text {
  color: white;
  font-size: 1rem;
  margin-bottom: 1vh;
}

.map-legend {
  position: absolute;
  top: 1vh;
  right: 1vw;
  background: rgba(31, 45, 61, 0.95); /* 深色半透明背景 */
  backdrop-filter: blur(10px);
  border-radius: 0.8vh;
  padding: 1vh;
  min-width: 12vw;
  box-shadow: 0 0.4vh 1.2vh rgba(0, 0, 0, 0.3); /* 加深阴影 */
  z-index: 100;
  border: 1px solid #2d3a4b; /* 深色边框 */
}

.legend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.8vh;
}

.legend-header h4 {
  margin: 0;
  font-size: 0.9rem;
  color: #bfcbd9; /* 深色主题主要文字 */
}

.legend-content {
  display: flex;
  flex-direction: column;
  gap: 0.5vh;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.8vw;
  font-size: 0.8rem;
}

.legend-marker {
  width: 1.2vw;
  height: 1.2vw;
  border-radius: 50%;
}

.legend-marker.radar {
  background: #409EFF;
}

.legend-marker.jammer {
  background: #E6A23C;
}

.legend-marker.ship {
  background: #67C23A;
}

.legend-marker.aircraft {
  background: #F56C6C;
}

.legend-label {
  flex: 1;
  color: #bfcbd9; /* 深色主题主要文字 */
}

.legend-count {
  background: rgba(64, 158, 255, 0.2); /* 半透明主题色背景 */
  color: #409EFF; /* 主题色 */
  padding: 0.2vh 0.5vw;
  border-radius: 1vh;
  font-weight: 500;
  min-width: 1.5vw;
  text-align: center;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* Element Plus 组件深色主题覆盖 */
:deep(.el-button) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

:deep(.el-button:hover) {
  background: #2d3a4b !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}

:deep(.el-button--primary) {
  background: #409EFF !important;
  border-color: #409EFF !important;
  color: #ffffff !important;
}

:deep(.el-button--primary:hover) {
  background: #66B2FF !important;
  border-color: #66B2FF !important;
}

:deep(.el-button-group .el-button) {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
}

:deep(.el-button-group .el-button:hover) {
  background: #2d3a4b !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}

/* 错误状态重试按钮样式 */
.retry-button {
  background: #263445 !important;
  border-color: #2d3a4b !important;
  color: #bfcbd9 !important;
  padding: 8px 20px !important;
  border-radius: 6px !important;
  font-size: 0.9rem !important;
}

.retry-button:hover {
  background: #2d3a4b !important;
  border-color: #409EFF !important;
  color: #409EFF !important;
}
</style>